//
//  JKRefreshView.swift
//  JKWeibo
//
//  Created by albert on 16/6/21.
//  Copyright © 2016年 albert. All rights reserved.
//  下拉刷新控件

import UIKit
import SnapKit

// 自定义的UIRefreshControl
class JKRefreshControl: UIRefreshControl {
    /** 懒加载刷新控件 */
    private lazy var refreshView: JKRefreshView = JKRefreshView.refreshView()
    
    override init() {
        super.init()
        // 1.添加子控件
        addSubview(refreshView)
        
        // 2.布局子控件
        refreshView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: 150, height: 50))
            make.center.equalTo(self)
        }
        
        // 3.监听UIRefreshControl frame改变
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        // 一定要记得移除
        removeObserver(self, forKeyPath: "frame")
    }
    
    // 重写endRefreshing
    override func endRefreshing() {
        super.endRefreshing()
        
        // 隐藏加载中的view
        refreshView.hideLoadingView()
    }
    
    // 记录是否需要旋转
    var rotationFlag = false
    
    // KVO监听frame的改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 通过观察发现：往下拉Y值越小，往上推，Y值越大
        
        if frame.origin.y == 0 || frame.origin.y == -64 {
            // 过滤垃圾数据
            return
        }
        
        // 正在刷新，显示加载中视图
        if refreshing {
            refreshView.showLoadingView()
        }
        
        if frame.origin.y > -60 && rotationFlag{
            rotationFlag = false
            JKLog("往下翻转，下拉刷新")
            refreshView.rotationArrow(rotationFlag)
            refreshView.refreshLabel.text = "下拉刷新"
            
        }else if frame.origin.y < -60 && !rotationFlag{
            rotationFlag = true
            JKLog("往上翻转，释放更新")
            refreshView.rotationArrow(rotationFlag)
            refreshView.refreshLabel.text = "释放更新"
        }
    }
}

// 刷新的控件
class JKRefreshView: UIView {
    
    /** 菊花 */
    @IBOutlet weak var loadingImageView: UIImageView!
    /** 提示视图 */
    @IBOutlet weak var tipView: UIView!
    /** 箭头 */
    @IBOutlet weak var arrowImageView: UIImageView!
    /** 下拉刷新，释放更新的label */
    @IBOutlet weak var refreshLabel: UILabel!
    
    // 类方法快速创建
    class func refreshView() -> JKRefreshView {
        return NSBundle.mainBundle().loadNibNamed("JKRefreshView", owner: nil, options: nil).last as! JKRefreshView
    }
    
    // MARK: - 外部控制方法
    /** 旋转箭头 */
    func rotationArrow(flag: Bool) {
        
        /** 
         transform旋转动画默认是按照顺时针旋转的
         但是旋转时还有一个原则，就近原则
         就近原则：如果让箭头旋转180°，它会顺时针转，如果是旋转181°，它会逆时针旋转过去，因为逆时针更近
         */
        var angle: CGFloat = flag ? 0.01 : -0.01
        angle += CGFloat(M_PI)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.arrowImageView.transform = CGAffineTransformRotate(self.arrowImageView.transform, angle)
        }
    }
    
    /** 显示加载视图 */
    func showLoadingView() {
        
        // 0.隐藏tipView
        tipView.hidden = true
        
        if let _ = loadingImageView.layer.animationForKey("ayb") {
            // 如果已经添加过动画，就直接返回
            return
        }
        
        // 1.创建动画
        let animation = CABasicAnimation()
        
        // 2.设置动画属性
        animation.keyPath = "transform.rotation.z"
        
        animation.toValue = M_PI * 2
        animation.duration = 0.5
        animation.repeatCount = MAXFLOAT
        
        // 3.添加动画
        loadingImageView.layer.addAnimation(animation, forKey: "ayb")
    }
    
    /** 隐藏加载视图 */
    func hideLoadingView() {
        // 1.显示tipView
        tipView.hidden = false
        
        // 2.移除动画
        loadingImageView.layer.removeAllAnimations()
    }
}
